package cn.net.autocode.platform.table.service;

import cn.net.autocode.dbManager.Dao;
import cn.net.autocode.platform.config.SpringProfileConfig;
import cn.net.autocode.platform.design.webclient.AcWebClient;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.List;

/**
 * 数据信息同步
 */
@Configuration  //标记配置类
@EnableScheduling   //开启定时任务
@Slf4j
public class TableScheduled {

    private final Dao dictDao;
    private final TableServ tableServ;

    private final AcWebClient acWebClient;

    private final SpringProfileConfig profileConfig;

    public TableScheduled(@Qualifier("dictDao") Dao dictDao, TableServ tableServ, AcWebClient acWebClient, SpringProfileConfig profileConfig) {
        this.dictDao = dictDao;
        this.tableServ = tableServ;
        this.acWebClient = acWebClient;
        this.profileConfig = profileConfig;
    }

    @Scheduled(fixedDelay = 60000)
    public void execute(){
        if(!"dev".equals(profileConfig.getProfile())){
            return;
        }
        //查询数据
        try {
            List<String> ids = dictDao.queryListValue("select id from ac_table where is_sync='N'",String.class);
            for(String tableId:ids){
                try {
                    tableServ.syncToServer(tableId);
                } catch (Exception e) {
                    //throw new RuntimeException(e);
                }
            }

            //删除表信息
            List<String> delIds = dictDao.queryListValue("select table_name from ac_table_del",String.class);
            for(String tableName:delIds){
                JSONObject rs = acWebClient.delTable(tableName);
                if(rs.getIntValue("code")==1){
                    dictDao.executeUpdate("delete from ac_table_del where table_name=?",tableName);
                }else{
                    log.error(rs.getString("msg"));
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}
